package com.edoomath.api.web.controller.mailtask;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.result.HttpResult;
import com.edoomath.api.servcice.MatrialService;
import com.edoomath.api.servcice.UserService;
import com.edoomath.entity.course.CourseMaterail;
import com.edoomath.entity.user.User;
import com.edoomath.entity.usercourse.UserCourseMaterial;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/download-file")
public class DownloadFileController {
	
	@Autowired
	private MatrialService materialService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 
	 * @param unionid
	 * @param materialIds
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public HttpResult cretae(@RequestParam(value = "unionid") String unionid,
							 @RequestParam("materialId") List<Long> materialIds,
							 @RequestParam(value = "extraMaterialId", required = false) List<Long> extraMaterialIds) {

		HttpResult httpResult = new HttpResult();
		
		User user = userService.load(unionid);
		if(user.isChildren() && StringUtils.isNotBlank(user.getMobile())) {
    		user = userService.getParent(user);
    		unionid = user.getUnionid();
    	}
		
		List<UserCourseMaterial> userCourseMaterials = materialService.generateCopyUrl(unionid, materialIds);
		
		List<CourseMaterail> materails = new ArrayList<CourseMaterail>(); 
		for(UserCourseMaterial userCourseMaterial : userCourseMaterials) {
			CourseMaterail newMaterial = new CourseMaterail(userCourseMaterial);
			materails.add(newMaterial);
		}
		
		if(CollectionUtils.isNotEmpty(extraMaterialIds)) {
			UserCourseMaterial userCourseMaterial = materialService.generateExtraTaskUrl(unionid, extraMaterialIds);
			httpResult.data("extraMaterials", userCourseMaterial);
		}
		
		return httpResult.success()
						 .data("materails", materails)
						 .message("创建链接成功");
	}

}
